package com.xxwy.springboot.webflux.controller;

import com.xxwy.springboot.webflux.exception.CheckException;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;

/**
 * @author xxwy
 * on 2018/8/17 0017
 */
@ControllerAdvice
public class CheckAdvice {

    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity handleBindingResult(WebExchangeBindException ex){

        return new ResponseEntity<String>(toStr(ex),HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(CheckException.class)
    public ResponseEntity handleCheckException(CheckException ex){

        return new ResponseEntity<String>(toStr(ex),HttpStatus.BAD_REQUEST);
    }

    private String toStr(CheckException ex) {
        return ex.getFieldName() + "  "+ex.getFieldValue();
    }

    private String toStr(WebExchangeBindException ex) {
        return ex.getFieldErrors().stream()
                .map(e -> e.getField() + ":" +e.getDefaultMessage())
                .reduce("",(s1,s2)->s1+"\n"+s2);
    }

}
